import { Button, View } from "@tarojs/components"
import React from "react"
import Taro from "@tarojs/taro"
import "./index.scss"
import http from "../../utils/http"
import { setLoginUser } from "../../utils"

export default function Home() {
  const login = e => {
    Taro.showLoading()
    const rawData = JSON.parse(e.detail.rawData)
    Taro.login({
      success: async function (res) {
        if (res.code) {
          const { data } = await http.post("/core/login/wechatLogin", {
            userRole: "0",//登录时未知当前人是什么角色
            wxcode: res.code,
          })
          //客户端微信登录获取到服务器的<sessionId、session>后，session存入客户端本地
          Taro.setStorageSync("sessionId", data.sessionId)
          //当前用户获取到的昵称+头像更新到后台数据库
          await http.post("/core/user/updateUserInfo", {
            userName: rawData.nickName,
            avatar: rawData.avatarUrl,
          })
          getUserInfo()
          Taro.showToast({
            title: "登录成功",
            icon: "success",
          })
          setTimeout(() => {
            Taro.navigateBack()
          }, 1500)
        } else {
          console.log("登录失败！" + res.errMsg)
        }
      },
      fail: function (res) {
        console.log(res)
      },
    })
  }
  //利用登录后， 通过sessionId去后台查询完整UserInfo信息
  const getUserInfo = async () => {
    const { data } = await http.get("/core/user/getUserInfoAndRefreshSession")
    if (data) {
      setLoginUser(data)//当前用户信息存入到客户端本地
    }
  }

  return (
    <View className="page-login">
      {/* <Button
        className="login-btn phone"
        openType="getPhoneNumber"
        onGetPhoneNumber={e => {
          console.log(e)
        }}
      >
        获取手机号
      </Button> */}
      <Button className="login-btn" openType="getUserInfo" onGetUserInfo={login}>
        登录
      </Button>
    </View>
  )
}
